package com.fjph.myapplication.ui.activity

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.net.http.SslError
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.FragmentActivity
import android.text.TextUtils
import android.view.View
import android.webkit.*
import android.widget.ProgressBar
import android.widget.RelativeLayout
import com.fjph.myapplication.R
import kotlinx.android.synthetic.main.activity_web_view.*
import com.fjph.myapplication.model.StoriesBean
import com.fjph.myapplication.R.id.img
import com.fjph.myapplication.model.DetailBean
import com.fjph.myapplication.model.ZhihuBean
import com.google.gson.Gson
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.lzy.okgo.request.base.Request


class WebViewActivity : FragmentActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_web_view)
        initView()
    }


    /**
     * 初始化
     */
    protected fun initView() {

        initWebView();
        val storiesId = intent.getIntExtra("stories", 0)
        getData(storiesId)

    }

    private fun initWebView() {

        val webSettings = web_view!!.settings
        webSettings.useWideViewPort = true// 设置此属性，可任意比例缩放
        webSettings.loadWithOverviewMode = true
        webSettings.javaScriptEnabled = true

        //开启 localstorage存储
        web_view!!.settings.domStorageEnabled = true
        web_view!!.settings.setAppCacheMaxSize((1024 * 1024 * 8).toLong())
        val appCachePath = applicationContext.cacheDir.absolutePath
        web_view!!.settings.setAppCachePath(appCachePath)
        web_view!!.settings.setAppCacheEnabled(true)

        web_view!!.clearCache(true)//清除缓存
        web_view!!.webViewClient = object : WebViewClient() {

            override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
                handler.proceed()  // 接受信任所有网站的证书
            }

            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {


                if (url.startsWith("tel:")) {
                    val intent = Intent(Intent.ACTION_DIAL, Uri.parse(url))
                    startActivity(intent)
                    return true
                }
                view.loadUrl(url)
                return true
            }

        }

        //webview自动适配
        webSettings.javaScriptCanOpenWindowsAutomatically = true

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { //16
            webSettings.allowFileAccess = true
            webSettings.allowFileAccessFromFileURLs = true
            webSettings.allowUniversalAccessFromFileURLs = true
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {//17
            webSettings.mediaPlaybackRequiresUserGesture = false
        }

        // android 5.0以上默认不支持Mixed Content
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            web_view!!.settings.mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
        }


        //提高渲染的优先级
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH)
        //不阻止图片网络数据
        webSettings.blockNetworkImage = false

        //开启调试
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true)
        }
    }

    override fun onBackPressed() {
        if (web_view!!.canGoBack()) {
            web_view!!.goBack()
        } else {
            finish()
        }
    }

    override fun onDestroy() {
        webview_root!!.removeView(web_view)
        web_view!!.removeAllViews()
        web_view!!.destroy()
        super.onDestroy()
    }


    fun getData(id: Int) {
        // http://news-at.zhihu.com/api/4/news/3892357

        OkGo.get<String>("http://news-at.zhihu.com/api/4/news/$id").execute(object : StringCallback() {

            override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
                super.onStart(request)
            }

            override fun onFinish() {
                super.onFinish()
            }

            override fun onError(response: Response<String>?) {
                super.onError(response)
            }

            override fun onSuccess(response: Response<String>?) {

                val data = (response?.body() ?: "");
                val bean = Gson().fromJson(data, DetailBean::class.javaObjectType)
                web_view.loadData(formatHtml(bean), "text/html; charset=UTF-8", null)
            }

        });

    }

    private fun loadCss(csss: List<String>, jss: List<String>): String {

        var loadJsCss = ""
        for (css in csss) {
            loadJsCss += String.format(" <link href=\"%s\" rel=\"stylesheet\" type=\"text/css\" /> ", css)
        }
        for (js in jss) {
            loadJsCss += String.format("<script src=\"%s\" type=\"text/javascript\"></script>", js)
        }
        return loadJsCss
    }

    /**
     * @return 格式化html
     * 关于这一段html的作用介绍：
     * 兼容手机端 自动换行，图片自适应，页面适应
     */
    private fun formatHtml(tempmodel: DetailBean): String {
        var temp = "<html><head><meta name=\"viewport\" content=\"width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\">"
        temp += "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"
        temp += "<meta name=\"format-detection\" content=\"telephone=no\" />"
        temp += loadCss(tempmodel.css!!, tempmodel.js!!)
        temp = "$temp<style type='text/css'>.headline .img-place-holder{height: 0px;} }</style>"
        temp = (temp
                + "</head><body>" + tempmodel.body
                + "</body></html>")// 添加图片自适应样式代码
        return temp
    }


}
